<?php
class ReviewsComments extends CActiveRecord {
    
    public $comId; 
    public $userId;
    public $revId;
    public $date;
    public $text;
    public $isAnonym;
    public $parentId;
    public $isDelegate;
    
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'reviews_comments';
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        if($this->getIsNewRecord()) {
            $revUserId = Yii::app()->db->createCommand()->select('userId')->from('reviews')->where('revId='.$this->revId)->queryRow();
            $this->isNew = $revUserId['userId'] == Yii::app()->user->getId() ? 0 : $revUserId['userId'];
            $this->date = time();
            $this->userId = Yii::app()->user->getId();
        }
        return true;
    }
    
    public function afterSave() {
        Yii::app()->db->createCommand('UPDATE `reviews` SET `countComments`=countComments + 1 WHERE `revId`="'.$this->revId.'"')->query();
    }
    
    public function rules() {
        return array(
            array('text', 'required', 'message' => '{attribute} не может быть пустым'),
            array('isAnonym, isDelegate, revId, parentId', 'safe')
        );
    }
    
    public function attributeLabels() {
        return array (
            'text' => 'Текст комментария',
        );
    }
    
    public function relations() {
        return array(
            'comUser' => array(self::BELONGS_TO, 'User', array('userId'=>'userid')),
        );
    }
}
